import React from "react"
import { Link } from "gatsby"

import s from "./pagination.module.css"

const SHOW_PAGES = 2
export const TurnPage = ({ previous, next, path }) => {
	return (
		<ul className={s.turnPage}>
			<li>
				{previous && (
					<span
						className={s.link}
						onClick={() => window.location.href = `${path}/${previous.type}/${previous.mongodb_id}`}
					>
						上一篇：{previous.title}
					</span>
				)}
			</li>
			<li>
				{next && (
					<span
						className={s.link}
						onClick={() => window.location.href = `${path}/${next.type}/${next.mongodb_id}`}
					>
						下一篇：{next.title}
					</span>
				)}
			</li>
		</ul>
	)
}

export default ({ currentPage, numPages, linkList }) => {
	const startIdx = currentPage - SHOW_PAGES > 0 ? currentPage - SHOW_PAGES : 0
	const endIdx =
		currentPage + SHOW_PAGES > linkList.length
			? linkList.length
			: currentPage + SHOW_PAGES
	const list = linkList.map((l, idx) => ({ idx, link: l }))

	return (
		<div className={s.pagination}>
			<div className={s.pages}>
				<div className={s.content}>
					{startIdx > 0 && (
						<>
							<Link to={list[0].link} className={s.pageNumber}>
								1
							</Link>
							<div className={s.numPages}>···</div>
						</>
					)}
					{list.slice(startIdx, currentPage).map(({ link, idx }) => (
						<Link
							key={link}
							to={link}
							className={
								currentPage === idx + 1
									? s.nowPageNumber
									: s.pageNumber
							}
						>
							{idx + 1}
						</Link>
					))}
					{list.slice(currentPage, endIdx).map(({ link, idx }) => (
						<Link
							key={link}
							to={link}
							className={
								currentPage === idx + 1
									? s.nowPageNumber
									: s.pageNumber
							}
						>
							{idx + 1}
						</Link>
					))}
					{endIdx < linkList.length && (
						<>
							<div className={s.numPages}>···</div>
							<Link
								className={s.pageNumber}
								to={list[list.length - 1].link}
							>
								{linkList.length}
							</Link>
						</>
					)}
				</div>
			</div>
		</div>
	)
}
